package com.reliable.service.utils;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@Slf4j
@Component
public class SftpUploader {

    @Value("${sftp.host}")
    private String host;

    @Value("${sftp.port}")
    private int port;

    @Value("${sftp.username}")
    private String username;

    @Value("${sftp.password}")
    private String password;

    @Value("${sftp.remote-dir}")
    private String remoteDir;

    @Value("${sftp.timeout:10000}")
    private int timeout;

    private ChannelSftp sftpChannel;
    private Session session;

    @PostConstruct
    public void init() {
        log.info("SftpUploader initialized with host: {}, port: {}, user: {}", host, port, username);
    }

    /**
     * 上传本地文件到 SFTP 服务器
     *
     * @param localFile 本地文件
     * @param remoteFileName 远程文件名（不含路径）
     * @throws Exception 上传异常
     */
    public void upload(File localFile, String remoteFileName) throws Exception {
        connect();
        try {
            sftpChannel.cd(remoteDir);
            try (InputStream inputStream = new FileInputStream(localFile)) {
                sftpChannel.put(inputStream, remoteFileName);
            }
            log.info("SFTP 上传成功: {} -> {}/{}", localFile.getAbsolutePath(), remoteDir, remoteFileName);
        } catch (Exception e) {
            log.error("SFTP 上传失败: {}", e.getMessage(), e);
            throw e;
        } finally {
            disconnect();
        }
    }

    private void connect() throws JSchException {
        JSch jsch = new JSch();
        session = jsch.getSession(username, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setTimeout(30000); // 30秒
        log.info("Connecting to {}:{} as {}", host, port, username);
        session.connect(30000);
        log.info("Session connected");

        Channel channel = session.openChannel("sftp");
        channel.connect(30000);
        sftpChannel = (ChannelSftp) channel;
        log.info("SFTP channel opened");
    }

    private void disconnect() {
        if (sftpChannel != null && sftpChannel.isConnected()) {
            sftpChannel.disconnect();
        }
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }
}